// shopPages/shopxq/shopxq.js
var app = getApp();
var page = 1;
var selectedNews = false;
var newsList = [];
var newCatid = [];

var sliderWidth = 38;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wei_height:'1200',
    posit:'-1',
    red_num:9,
    mall_picture: '',
    mall_url: '',
    selected: true,
    goodsList: [],
    isowner: false,
    gg_yiny: false,
    //微信小程序动画
    animationData: {},
    animationisno: false,
    guilist: {},
    arrId: [],
    arrName: [],
    textStates: ["view-btns-text-normal", "view-btns-text-select"],
    min: 1,//最小值 整数类型，null表示不设置
    max: null,//最大值 整数类型，null表示不设置
    num: 1,//输入框数量 整数类型
    change: 1,//加减变化量 整数类型
    def_num: 1,//输入框值出现异常默认设置值
    spec_status: 0,
    //数据格式
    goods_spec_list: [],
    spec_goods_price: [],
    goods_attr_list: [],
    comment: [],
    // 选项卡
    tabs: ["菜单", "评价", "商家"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    nav_item_h: 41,//菜单元素高度,来自css设置
    box_itemh_h: 30,//内容区菜单头高度,来自css设置
    box_itemc_h: 84,//内容区每项高度,来自css设置
    scrollTop: 0,//菜单滚动条默认位置
    navlistIdx: "id0",//菜单默认标记位置
    navlist: [],
    toView: "id0",//内容区默认位置
    datalist: [],
    itemscrolltop: [],//存放内容区每块内容所在的滚动条位置区间
    guilist:[],
    goods_index:-1,
    list_index:-1,
    can_buy: false,
    comment:[],
    more_status: false,
  },
  // 选择规格页面弹出   微信小程序动画
  guigeselect: function (e) {
    let that = this;
  
    var goods = that.data.goodsList[e.currentTarget.dataset.goods_index].list[e.currentTarget.dataset.list_index];
    // console.log(goods);
    
    let animal1 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, -600).step({
      duration: 500
    })
    that.setData({
      goods_spec: goods.goods_spec_list,
      spec_goods_price: goods.spec_goods_price,
      animationData: animal1.export(),
      gg_yiny: true,
      img_url: goods.img_url,
      title: goods.title,
      examine_status: goods.examine_status,
      guilist: [],
      selectGuigeName: [],
      arrId:[],
      arrName:[],
      goods_attr_list:[],
      num:1,
      goods_index: e.currentTarget.dataset.goods_index,
      list_index:e.currentTarget.dataset.list_index,
      goods_id: e.currentTarget.dataset.goods_id,
      spec_status: e.currentTarget.dataset.spec_status
    })
  },
  // 选择规格页面隐藏   微信小程序动画
  guigeno: function () {
    let that = this
    let animal1 = wx.createAnimation({
      timingFunction: 'ease-in'
    }).translate(0, 600).step({
      duration: 500
    })
    that.setData({
      animationData: animal1.export(),
      gg_yiny: false,
     
    })
    if (that.data.goods_spec != undefined) {
      var goods_spec = that.data.goods_spec;

      for (let i = 0; i < goods_spec.length; i++) {
        for (let j in goods_spec[i]) {
          goods_spec[i][j].isClick = 0;
        }

      };
      console.log(goods_spec);
      that.setData({
        goods_spec: goods_spec
      });
    }
  },
  //输入框失去焦点事件
  evblur: function (e) {
    var zval = parseInt(e.detail.value);
    // console.log(zval)
    //正则 正整数 0 负整数
    if (/(^-[1-9][0-9]{0,}$)|(^0$)|(^[1-9][0-9]{0,}$)/.test(zval)) {
      //最大值
      if (this.data.max != null) {
        if (zval > this.data.max) {
          console.log("超出最大值")
          this.setData({ num: this.data.def_num })
        } else {
          this.setData({ num: zval })
        };
      } else {
        this.setData({ num: zval })
      };
      //最小值
      if (this.data.min != null) {
        if (zval < this.data.min) {
          console.log("低于最小值")
          this.setData({ num: this.data.def_num })
        } else {
          this.setData({ num: zval })
        };
      } else {
        this.setData({ num: zval })
      };
    } else {
      console.log("不是整数")
      this.setData({ num: this.data.def_num })
    };
  },
  //加
  bindAddCardTap:function(e){
    var that = this;
    var goods_id = e.currentTarget.dataset.goods_id;
    var goods_name = e.currentTarget.dataset.goods_name;
    var spec_status = e.currentTarget.dataset.spec_status;
    var num = spec_status > 0 ? that.data.num : 1;
    if (spec_status > 0 && that.data.guilist.id == undefined) {
      if (that.data.gg_yiny == true) {
        wx.showToast({
          title: '请选择规格!',
          icon: 'none',
          duration: 1000
        })
      }
      return false;
    }
    var goods = that.data.goodsList[e.currentTarget.dataset.goods_index].list[e.currentTarget.dataset.list_index];
    // console.log(goods);
    if (parseInt(goods.remain_mount) < 1 && spec_status == 0) {
      wx.showToast({
        title: '商品数量不足!',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (that.data.guilist.id == undefined && spec_status > 0) {
      wx.showToast({
        title: '请选择规格!',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (num > that.data.guilist.store_count && spec_status > 0) {
      wx.showToast({
        title: '商品数量不足!',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else {
      var spec_price_id = 0;
      if (spec_status > 0) {
        spec_price_id = that.data.guilist.id
      }

      var that = this;
      var url2 = '/cart/add_v4';
      var params2 = {
        uid: app.globalData.userInfo.id,
        goods_id: goods_id,
        spec_price_id: spec_price_id,
        num: num,
        timestamp: new Date().getTime(),
      };
      params2.sign = app.getSign(params2)
      app.HttpGetSend(url2, params2, function (res) {
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 31, goods_name)
          app.radarAdd(app.globalData.SwitchTabParams.v_id, 31, 0, goods_name, app.globalData.userInfo.logo)
          app.showTipMsg('添加至购物车');
          if (that.data.goods_spec != undefined) {
            var goods_spec = that.data.goods_spec;

            for (let i = 0; i < goods_spec.length; i++) {
              for (let j in goods_spec[i]) {
                goods_spec[i][j].isClick = 0;
              }

            };
            console.log(goods_spec);
            that.setData({
              goods_spec: goods_spec
            });
          }
          that.setData({
            can_buy:true
          });
        }
      });

    }
  },

  bindAddCardTap1: function (e) {
    var that = this;
    var goods_id = that.data.goods_id;
    var spec_status = that.data.spec_status;
    var examine_status = that.data.examine_status;
    if (examine_status==0){
      wx.showToast({
        title: '商品审核中',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    var num = spec_status > 0 ? that.data.num : 1;
    if (spec_status > 0 && that.data.guilist.id == undefined) {
      if (that.data.gg_yiny == true) {
        wx.showToast({
          title: '请选择规格!',
          icon: 'none',
          duration: 1000
        })
      }
      return false;
    }
    var goods = that.data.goodsList[that.data.goods_index].list[that.data.list_index];
    // console.log(goods);
    if (parseInt(goods.remain_mount) < 1 && spec_status == 0) {
      wx.showToast({
        title: '商品数量不足!',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (that.data.guilist.id == undefined && spec_status > 0) {
      wx.showToast({
        title: '请选择规格!',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else if (num > that.data.guilist.store_count && spec_status > 0) {
      wx.showToast({
        title: '商品数量不足!',
        icon: 'none',
        duration: 1000
      })
      return false;
    } else {
      var spec_price_id = 0;
      if (spec_status > 0) {
        spec_price_id = that.data.guilist.id
      }

      var that = this;
      var url2 = '/cart/add_v4';
      var params2 = {
        uid: app.globalData.userInfo.id,
        goods_id: goods_id,
        spec_price_id: spec_price_id,
        num: num ,
        timestamp: new Date().getTime(),
      };
      params2.sign = app.getSign(params2)
      app.HttpGetSend(url2, params2, function (res) {
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          app.showTipMsg('添加至购物车');
          app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 31, goods.title)
          app.radarAdd(app.globalData.SwitchTabParams.v_id, 31, 0, goods.title + '(规格：' + that.data.selectGuigeName[0] + ',' + that.data.selectGuigeName[1] + ')', app.globalData.userInfo.logo)

          if (that.data.goods_spec != undefined){
            var goods_spec = that.data.goods_spec;

            for (let i = 0; i < goods_spec.length; i++) {
              for (let j in goods_spec[i]){
                goods_spec[i][j].isClick = 0;
              }
              
            };
            console.log(goods_spec);
            that.setData({
              goods_spec: goods_spec
            });
          }
         
          that.guigeno();
          that.setData({
            can_buy: true
          });
        }
      });

    }
  },

  evad: function (e) {
    var cval = Number(this.data.num) + this.data.change;
    if (this.data.max != null) {
      if (cval > this.data.max) {
        console.log("超出最大值")
      } else {
        this.setData({ num: cval })
      };
    } else {
      this.setData({ num: cval })
    };
    
  },
  //减
  evic: function () {
    var cval = Number(this.data.num) - this.data.change;
    if (this.data.min != null) {
      if (cval < this.data.min) {
        console.log("低于最小值")
      } else {
        this.setData({ num: cval })
      };
    } else {
      this.setData({ num: cval })
    };
  },
  selectGuige(e) {
    let that = this,
      // 获取第一个循环的index
      fuindex = e.currentTarget.dataset.fuindex,
      // 获取第二个循环的index
      chindex = e.currentTarget.dataset.chindex,
      // 获取当前点击的id
      selectId = e.currentTarget.dataset.id,
      // 获取当前点击的规格名称
      selectName = e.currentTarget.dataset.item,
      //  初始化arrId
      arrId = that.data.arrId,
      //  初始化arrName
      arrName = that.data.arrName,
      guilists = {},
      goods_spec = that.data.goods_spec;

    // 通过循环来判断点击了哪一个规格，根据数据结构来；
    // goods_spec[fuindex]根据fuindex来判断点击了哪一种类型的规格
    for (let i = 0; i < goods_spec[fuindex].length; i++) {
      // 当i等于当前点击的规格时，设置isClick=1
      if (i == chindex) {
        goods_spec[fuindex][i].isClick = 1;
      }
      // 否则设置其他的isClick=0
      else {
        goods_spec[fuindex][i].isClick = 0;
      }
    };
    // 把点击的规格名称和规格id存起来
    arrId[fuindex] = selectId;
    arrName[fuindex] = selectName;

    // 拼接规格id，（后台返回的数据是这个）
    let selectGuigeId = arrId.join('_');
    for (let i = 0; i < that.data.spec_goods_price.length; i++) {
      // 找对应的规格组合
      if (that.data.spec_goods_price[i].key == selectGuigeId) {
        guilists = that.data.spec_goods_price[i];
      }
    }
    // console.log(goods_spec);
    that.setData({
      goods_spec: goods_spec,
      arrId,
      guilist: guilists,
      selectGuigeName: arrName
    })
  },
  numChange(e) {
    this.setData({
      num: e.detail.value
    })
  },
  queDing() {
    let that = this;
    let selectguigeid = that.data.arrId.join('_');
    for (let i = 0; i < that.data.spec_goods_price.length; i++) {
      // 判断是否选择规格
      if (that.data.spec_goods_price[i].key == selectguigeid) {
        wx.showModal({
          showCancel: false,
          content: '选择成功',
          success: function (res) { }
        });
        // 判断库存是否充足
        if (selectguigeid.store_count <= 0) {
          wx.showModal({
            showCancel: false,
            content: '库存不足',
            success: function (res) { }
          });
        }
        // 两种情况满足跳转
        else {
          wx.showModal({
            showCancel: false,
            content: '跳转页面',
            success: function (res) { }
          });
        }
        return
      } else {
        wx.showModal({
          showCancel: false,
          content: '请选择规格',
          success: function (res) {
            if (res.confirm) { }
          }
        })
      }
    }
  },
  //计算存放内容区每块内容所在的滚动条位置区间
  computeritemscrolltop: function (goodsList) {
    var h = -10;
    for (var i = 0; i < goodsList.length; i++) {
      var id = goodsList[i].id;
      h = h + this.data.box_itemh_h;
      for (var j = 0; j < goodsList[i].list.length; j++) {
        h = h + this.data.box_itemc_h;
      };
      var arr = this.data.itemscrolltop;
      arr.push({ id: id, scrolltoph: h })
      this.setData({ itemscrolltop: arr })
    };
    console.log(this.data.itemscrolltop)
  },
  //菜单点击
  skip: function (event) {
    //console.log(event.target.dataset.id)
    this.setData({ toView: event.target.dataset.id })
    this.setData({ navlistIdx: event.target.dataset.id })
  },
  //内容区滚动
  scroll: function (event) {
    // console.log(event.detail.scrollTop)
    // console.log(this.data.itemscrolltop)
    for (var i = 0; i < this.data.itemscrolltop.length; i++) {
      if (event.detail.scrollTop < this.data.itemscrolltop[i].scrolltoph) {

        this.setData({ navlistIdx: this.data.itemscrolltop[i].id })
        this.setData({ scrollTop: i * this.data.nav_item_h - 2 * this.data.nav_item_h })
        break;
      };
    };

  },
  //点击进入名片
  showCarte: function (e) {
    wx.switchTab({
      url: '/pages/carteShow/carteShow'
    })
  },
  //点击进入详情页面
  bindGoodsTap: function (e) {
    var id = e.detail.button_typId;
    var title = e.detail.button_status;
    wx.navigateTo({
      url: '../../pages/goodsDetail/goodsDetail?id=' + id + '&title=' + title,
    })
  },
  //点击购物车图标进入购物车页面
  bindBuyCarTap: function (e) {
    wx.switchTab({
      url: '/pages/buyCar/buyCar',
    })
  },
  bindBuyCarTap1: function (e) {
    wx.navigateTo({
      url: '/pages/orderSure/orderSure?select_mgid='+this.data.info.mgid
    })
  },
  //获取商品列表
  getGoodsList: function () {
    wx.showLoading({
      title: '数据加载中',
    })
    var that = this;
    var url2 = '/shop_api/index_person_mall';
    var params2 = {
      uid: app.globalData.SwitchTabParams.v_id,
      pagesize: 20,
      pageno: page
    };
    var more_status = that.data.more_status;
    app.HttpPostSend(url2, params2, function (res) {
      wx.hideLoading();
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
        selectedNews = false;
        that.setData({
          goodsList: [],
          navlist:[]
        })
      } else {
        var goodsList = res.data.lists.datalist_arr;
        for (let i = 0; i < goodsList.length; i++) {
          newsList.push(goodsList[i]);
        }
        var catList = res.data.lists.cat_id_arr;
        for (let i = 0; i < catList.length; i++) {
          newCatid.push(catList[i]);
        }
        if (res.data.lists.buy>0){
          that.setData({
            can_buy:true

          })
        }
        if (res.data.lists.comment.length<4){
          more_status = false;
        }else{
          more_status = true;
          page += 1;
          
        }
        that.setData({
          goodsList: newsList,
          more_status: more_status,
          navlist:newCatid,
          info: res.data.lists.manager_info,
          comment: res.data.lists.comment
        })
        wx.setNavigationBarTitle({
          title: res.data.lists.manager_info.company
        })
        //计算存放内容区每块内容所在的滚动条位置区间
        that.computeritemscrolltop(newsList);
        // console.log(newCatid);
        if (app.globalData.SwitchTabParams.v_id != app.globalData.userInfo.id){
          app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 13, '')
        }
        
        wx.hideLoading();
      }
    });
  },
  // 全屏展示图片
  showPicture: function (e) {
    // console.log(e)
    let img_src = e.currentTarget.dataset.src
    wx.previewImage({
      current: img_src, // 当前显示图片的http链接
      urls: [img_src] // 需要预览的图片http链接列表
    })
  },
  
  //点击咨询图标进入咨询聊天页面
  bindSocksTap: function (e) {
    wx.navigateTo({
      url: '/pages/socks/socks?mid=' + this.data.info.id
    })
    app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 6, '')
  },
  //点击购物车图标进入购物车页面
  bindBuyCarTap: function (e) {
    wx.switchTab({
      url: '/pages/buyCar/buyCar',
    })
    // wx.navigateTo({
    //   url: '../buyCar/buyCar?uid=' + app.globalData.userInfo.id
    // })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
    if (options.mid != undefined && options.mid != 'undefined') {
      app.globalData.SwitchTabParams.v_id = options.mid;
    }
  
    page = 1;
    selectedNews = false;
    newsList = [];
    newCatid = [];
    that.getGoodsList();
  },
  // 点击进去咨询页面
  bindGoSocksTap: function (e) {
    wx.navigateTo({
      url: '../../pages/socks/socks',
    })
  },
  //跳转全部评价
  bindpingjia:function(){
    wx.navigateTo({
      url: '../AllPjia/AllPjia',
    })
  },
  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
    
  },
  bindBuyTap:function(){
    wx.switchTab({
      url: '../buyCar/buyCar?uid=' + app.globalData.userInfo.id
    })
  },

  getMoreComment:function(){
    wx.showLoading({
      title: '数据加载中',
    })
    var that = this;
    var url2 = '/shop_api/get_more_comment';
    var params2 = {
      mgid: that.data.info.mgid,
      pageno: page
    };
    var more_status = that.data.more_status;
    app.HttpPostSend(url2, params2, function (res) {
      wx.hideLoading();
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
       
      } else {
        var old_comment = that.data.comment;
        var comment = res.data.lists.comment;
        // console.log(comment);
        for (let i = 0; i < comment.length; i++) {
          old_comment.push(comment[i]);
        }
       
        if (comment.length < 6) {
          more_status = false;
        } else {
          more_status = true;
          page += 1;
          that.setData({
            page: page
          });
        }
        that.setData({
          comment: old_comment,
          more_status: more_status,
        })
        wx.hideLoading();
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 配置iphone X
    var that = this;
    wx.getSystemInfo({
      success: res => {
        // console.log('手机信息res'+res.model)
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          that.setData({
            wei_height: '1200'
          });
        }
      }
    })
    // 页面显示
    if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id) {

      // 雷达添加查看记录 -查看商城数
      app.radarAdd(app.globalData.SwitchTabParams.v_id, 4, '', '', app.globalData.userInfo.logo)

      // 发送模板消息-访客到访通知
      app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter?coming_status=1', '正在访问个人商城', '', '', '')
      this.setData({
        isowner: true
      })
    } else {
      this.setData({
        isowner: false
      })
    }

  },

  toGoodsDetail: function (e) {
    wx.navigateTo({
      url: "/pages/goodsDetail/goodsDetail?id=" + e.currentTarget.dataset.id
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /** 
  * 页面上拉触底事件的处理函数 
  */
  onReachBottom: function () {
    var that = this;
    // console.log(that.data.more_status);
    if (that.data.more_status == true && that.data.activeIndex == 1) {
      var that = this;
      // 显示加载图标  
      wx.showLoading({
        title: '玩命加载中',
      })
      // 页数+1  
      that.getMoreComment();

    } else {
      wx.hideLoading();
    }
  },
})